
<template>
  <div >
        <main>
          <div class="page_content" v-if="check_tab == 0">
            <div class="content">
              <textarea
                name
                id
                cols="30"
                rows="10"
                ref="translate_focus"
                v-model="input_translate"
                placeholder="请输入翻译内容"
                @keyup.enter="translate"
              ></textarea>
              <textarea
                name
                id
                cols="30"
                rows="10"
                v-model="output_translate"
              ></textarea>
              <button @click="translate">翻译</button>
            </div>
            <div class="list">
              <ul>
                <li>历史记录</li>
                <li v-for="item in history_translate" :key="item._id">
                  <a href="#" @click="check_history_translate(item._id)">{{
                    item.pattern
                  }}</a>
                </li>
              </ul>
            </div>
          </div>

          <div v-if="check_tab == 1">
            <textarea
              name
              id
              cols="30"
              rows="10"
              v-model="inputjs"
              placeholder="请输入密文"
            ></textarea>
            <textarea name id cols="30" rows="10" v-model="outputjs"></textarea>
            <button @click="js_beautify">解密</button>
          </div>
          <div v-if="check_tab == 2">
            <div>
              <label>当前时间：{{ datetime }}</label>
              <button @click="get_time">刷新</button>
            </div>

            <div>
              时间戳对比
              <br />例1： 1564837873-1565701907
              <br />例2：1564837873123-1565701907515
              <input
                type="text"
                placeholder="请输入时间戳 "
                v-model="timestamp"
              />
              <button @click="cal_stamp">计算</button>
            </div>

            <div>
              时间：
              <span>{{ new_timetodate }}</span>
            </div>
            <div v-if="difference">
              毫秒差：
              <span>{{ difference }}</span
              >秒
            </div>
            <div v-if="diffdate">
              时间差：
              <span>{{ diffdate.days }}</span
              >天 <span>{{ diffdate.hours }}</span
              >时 <span>{{ diffdate.minutes }}</span
              >分 <span>{{ diffdate.seconds }}</span
              >秒
            </div>
          </div>
          <div v-if="check_tab == 3">
            驼峰转下划线
            <input type="text" v-model="in_undertoline" />
            <input type="text" v-model="out_undertoline" />
            <button @click="undertoline">转换</button>
            <br />下划线转驼峰
            <input type="text" v-model="in_linetounder" />
            <input type="text" v-model="out_linetounder" />
            <button @click="linetounder">转换</button>
            <br />转大写
            <input type="text" v-model="in_toupper" />
            <input type="text" v-model="out_toupper" />
            <button @click="toupper">转换</button>
            <br />转小写
            <input type="text" v-model="in_tolower" />
            <input type="text" v-model="out_tolower" />
            <button @click="tolower">转换</button>
          </div>

          
          <div
            v-show="check_tab == 1011 || lrc_full_screen == 1"
            v-if="loading_music"
          >
            <aplayer
              :class="{ lrc_full_screen: lrc_full_screen == 1 }"
              ref="player"
              theme="pic"
              repeat="list"
              showLrc
              :narrow="false"
              :music="music"
              :list="music_list"
              @play="play_event"
              @pause="pause_event"
              @playing="playing_event"
            />
            <!-- <aplayer   ref="player" autoplay :music="music" :list="music_list" showLrc="true" :narrow="false" theme="#b7daff" repeat="repeat-all" listmaxheight='96px'/>  -->
          </div>
        </main>
  </div>
</template>

<script>
import { ipcRenderer, remote } from "electron";
import { constants } from "fs";
import path from "path";
//翻译会用到数据库
import translateDb from "../../datastore/translate";
const fs = require("fs"); 
const { URL } = require("url");
import md5 from "js-md5";

//下面是音乐播放器
import VueAplayer from "vue-aplayer";


import noteDb from "../../datastore/note";

export default {
  name: "index",
  components: {
    //别忘了引入组件
    aplayer: VueAplayer
  },
  data() {
    return {
      check_tab: 0,
      window_max: 0,
      
      input_translate: "",
      output_translate: "",
      history_translate: {}, //历史翻译
      in_undertoline: "",
      out_undertoline: "",
      in_linetounder: "",
      out_linetounder: "",
      in_toupper: "",
      out_toupper: "",
      in_tolower: "",
      out_tolower: "",

      loading_music: 0, //是否加载完
      music_index: 0,
      music_ids: [], //防止歌曲列表重复
      music_list_obj: {},
      music_list: [],
      music: {
        // title: "王菲 - 红豆",
        // src: "file:/home/edison/Music/王菲 - 红豆.mp3",
        // lrc: "file:/home/edison/Music/王菲 - 红豆.lrc",
        // artist: "王菲",
        // pic: "file:/home/edison/Music/王菲 - 红豆.jpg"
      },
      lrc_full_screen: 0, //歌词全屏
      is_read: 0,
      is_play: 0,

     
    };
  },
  created: function() {
      setTimeout(() => {
          this.$refs.translate_focus.focus();
        }, 30);
    //监听主进程发来的消息
    this.$electron.ipcRenderer.on("main-process-messages", (event, arg) => {
      // if (arg == "show_window") {
      //   //加一点延时防止切换未完成找不到dom的情况
      //   setTimeout(() => {
      //     this.$refs.translate_focus.focus();
      //   }, 30);
      // }

      if (arg == "play_music") {
        this.aud_pllay(!this.is_play);
      }
      if (arg == "play_previous") {
        this.btn_previous();
      }
       if (arg == "play_next") {
        this.btn_next();
      }
    });
    // `this` 指向 vm 实例
    //查询翻译历史记录is_play
    this.get_history_translate();
    this.onload_music().then(() => {
      setTimeout(() => {
        this.music = this.music_list[this.music_index];
        this.loading_music = 1;
        
        setTimeout(() => {
          let aplayer = this.$refs.player;
          // aplayer.play();
          // this.is_play = 1;
        }, 50);
      }, 1000);
    });
    // fs.watch(
    //   remote.app.getPath("music"),
    //   { encoding: "buffer" },
    //   (eventType, filename) => {
    //     // if (filename) {
    //     //   console.log(filename);
    //     //   // 打印: <Buffer ...>
    //     // }
    //     this.onload_music();
    //   }
    // );

  },
  methods: {
    
    open(link) {
      this.$electron.shell.openExternal(link);
    },


  
    //翻译
    translate() {
      if (this.input_translate == "") {
        alert("请输入要翻译的内容");
      }

      //验证是否是中文
      let pattern = new RegExp("[\u4E00-\u9FA5]+");
      if (pattern.test(this.input_translate)) {
        var from = "zh";
        var to = "en";
      }
      //验证是否是英文
      let pattern2 = new RegExp("[A-Za-z]+");
      if (pattern2.test(this.input_translate)) {
        var from = "en";
        var to = "zh";
      }
      var query_base = this.input_translate;
      // 多个query可以用\n连接  如 query='apple\norange\nbanana\npear'
      var query = query_base.trim().replace(/[\r\n]/g, "\n"); //去掉两端空格并转换回车符
      query = query.replace(/[\r]/g, "\n");
      var that = this;
      that.output_translate = "";
      //查询是否已翻译过
      translateDb.findOne({ pattern: query }, function(err, docs) {
        if (!docs) {
          var appid = "20190815000326544";
          var key = "M9bxoZ7XLYmo9iHLpvEi";
          var salt = new Date().getTime();

          var str1 = appid + query + salt + key;

          var sign = md5(str1);
          that
            .$jsonp("https://fanyi-api.baidu.com/api/trans/vip/translate", {
              q: query,
              appid: appid,
              salt: salt,
              from: from,
              to: to,
              sign: sign
            })
            .then(response => {
              let add_time = parseInt(new Date().getTime() / 1000);
              translateDb.insert(
                { pattern: query, result: response, add_time: add_time },
                function(err, newDoc) {
                  // Callback is optional
                  // newDoc is the newly inserted document, including its _id
                  // newDoc has no key called notToBeSaved since its value was undefined
                }
              );
              response.trans_result.forEach(item => {
                that.output_translate += item.dst.toLowerCase() + "\n";
              });

              that.get_history_translate();
            })
            .catch(error => {});
        } else {
          docs.result.trans_result.forEach(item => {
            that.output_translate += item.dst.toLowerCase() + "\n";
          });
        }
        return;
      });

      return;
    },
    //历史翻译
    get_history_translate() {
      let that = this;
      translateDb
        .find({})
        .sort({ add_time: -1 })
        .exec(function(err, docs) {
          that.history_translate = docs;
        });
    },
    check_history_translate(id) {
      let that = this;
      translateDb.findOne({ _id: id }, function(err, docs) {
        that.output_translate = "";
        that.input_translate = "";
        docs.result.trans_result.forEach(item => {
          that.output_translate += item.dst.toLowerCase() + "\n";
        });
        that.input_translate = docs.pattern;
      });
    },

    //驼峰转下划线
    undertoline() {
      this.out_undertoline = this.in_undertoline
        .replace(/\B([A-Z])/g, "_$1")
        .toLowerCase();
    },
    //下划线or短横线转驼峰
    linetounder() {
      this.out_linetounder = this.in_linetounder.replace(/_([a-z])/g, function(
        all,
        letter
      ) {
        return letter.toUpperCase();
      });
    },
    toupper() {
      this.out_toupper = this.in_toupper.toUpperCase();
    },
    tolower() {
      this.out_tolower = this.in_tolower.toLowerCase();
    },
    

    refresh_music() {
      this.onload_music().then(() => {
        setTimeout(() => {
          this.music = this.music_list[this.music_index];
          this.loading_music = 1;

          setTimeout(() => {
            let aplayer = this.$refs.player;
            // aplayer.play();
            // this.is_play = 1;
          }, 50);
        }, 800);
      });
    },
    async onload_music() {
      let music_path = path.join(remote.app.getPath("music"));
      let in_array = function(search, array) {
        for (var i in array) {
          if (array[i] == search) {
            return true;
          }
        }
        return false;
      };
      //获取歌词和图片等
      let resources = (basename, ext) => {
        return new Promise((resolve, reject) => {
          let res_path = path.join(music_path, basename + "." + ext);
          fs.exists(res_path, exists => {
            if (exists) {
              resolve("file:" + res_path);
            } else {
              resolve(false);
            }
          });
        });
      };

      fs.readdir(music_path, (err, files) => {
        if (err) throw err;
        this.music_ids = [];
        
        files.forEach(file => {
          //拼接获取绝对路径，fs.stat(绝对路径,回调函数)
          let fPath = path.join(music_path, file);
          fs.stat(fPath, async (err, stat) => {
            if (stat.isFile()) {
              //如果是文件 （这里只需要读文件）
              //stat 状态中有两个函数一个是stat中有isFile ,isisDirectory等函数进行判断是文件还是文件夹
              //获取文件扩展名
              let exts = [".mp3", ".m4a"];
              let extname = path.extname(fPath); //扩展名
              let basename = path.basename(fPath).split(".")[0];
              //如果是音乐文件 并且音乐列表中没有这个文件
              if (in_array(extname, exts)) {
                //刷新标识数
                this.music_ids.unshift(md5(fPath));
                let music={};
                if (!this.music_list_obj[md5(fPath)]) {
                  //写入数组
                  music = {
                    title: basename,
                    src: "file:" + fPath,
                    mus_id: md5(fPath),

                    artist: basename.split("-")[0].trim()
                  };
                  let lrc = await resources(basename, "lrc");
                  let pic =
                    (await resources(basename, "jpg")) ||
                    (await resources(basename, "png"));

                  if (lrc) {
                    music.lrc = lrc;
                  }
                  if (pic) {
                    music.pic = pic;
                  }

                  this.music_list.unshift(music);
                  //如果默认播放音乐为空 则写入

                  this.music_list_obj[md5(fPath)] = music;
                }
              }
            }
            // else { //如果是目录
            //     myReadfile(fPath)
            // }
          });
        });

        //删除文件夹已经不存在的音乐 如果删除的是正在播放的音乐则 暂停播放切换到下一曲
        setTimeout(() => {
          let aplayer = this.$refs.player;
          var obj_music = aplayer.currentMusic; //获得播放器当前播放的音乐
          this.music_list.forEach((item, index) => {
            if (!in_array(item.mus_id, this.music_ids)) {
              this.music_list.splice(index, 1);
              delete this.music_list_obj[item.mus_id];
              if (item.mus_id == obj_music.mus_id) {
                this.btn_next();
                setTimeout(() => {
                  aplayer.pause();
                  this.is_play = 0;
                }, 60);
              }
            }
          });
          //刷新当前播放音乐索引
          this.music_list.forEach((item, index) => {
            if (item.mus_id == obj_music.mus_id) {
              this.music_index = index;
            }
          });
        }, 2000);
      });
    },
    aud_pllay(play) {
      let aplayer = this.$refs.player;
      if (play == 1) {
        aplayer.play();
      } else {
        aplayer.pause();
      }
      this.is_play = play;
    },
    play_event() {
      this.is_play = 1;
      //开始播放 同步当前播放歌曲索引
      let aplayer = this.$refs.player;
      var obj_music = aplayer.currentMusic; //获得播放器当前播放的音乐
      var obj_music_lict = JSON.parse(JSON.stringify(this.music_list));
      // var sum_music = obj_music_lict.length;
      obj_music_lict.forEach((item, index) => {
        if (item.mus_id == obj_music.mus_id) {
          this.music_index = index;
        }
      });
    },
    //暂停
    pause_event() {
      this.is_play = 0;
    },
    playing_event() {},
    //上一曲
    btn_previous() {
      let aplayer = this.$refs.player;
      var obj_music = aplayer.currentMusic; //获得播放器当前播放的音乐

      var obj_music_lict = JSON.parse(JSON.stringify(this.music_list));
      var sum_music = obj_music_lict.length;

      //先拿到当前播放的歌曲索引
      // obj_music_lict.forEach((item, index) => {
      //   if (item.mus_id == obj_music.mus_id) {
      //     this.music_index = index;
      //   }
      // });

      if (this.music_index == 0) {
        this.music_index = sum_music - 1;
      } else {
        this.music_index--;
      }
      this.music = this.music_list[this.music_index];

      setTimeout(() => {
        let aplayer = this.$refs.player;
        aplayer.play();
        this.is_play = 1;
      }, 50);
    },
    //下一曲
    btn_next() {
      var obj_music_lict = JSON.parse(JSON.stringify(this.music_list));
      var sum_music = obj_music_lict.length;
      if (this.music_index == sum_music - 1) {
        this.music_index = 0;
      } else {
        this.music_index++;
      }
      this.music = this.music_list[this.music_index];

      setTimeout(() => {
        let aplayer = this.$refs.player;
        aplayer.play();
        this.is_play = 1;
      }, 50);
    },
    
  }
};
</script>

<style>
/* 
#wrapper {
  height: 90vh;
  padding: 60px 80px;
  width: 100vw;
} */
button {
  font-size: 0.8em;
  cursor: pointer;
  outline: none;
  padding: 0.75em 2em;
  border-radius: 2em;
  display: inline-block;
  color: #fff;
  background-color: #4fc08d;
  transition: all 0.15s ease;
  box-sizing: border-box;
  border: 1px solid #4fc08d;
}

button.alt {
  color: #42b983;
  background-color: transparent;
}
</style>
